package com.yanx.common.page;

import com.yanx.common.utils.String_;
import com.yanx.common.utils.ThreadLocal_;

public class PageHelper {

    public static String getPageSql(String sql) {
        if (String_.equals(getPageType(), PageConstant.Type.CURSOR)) {
            // TODO CURSOR分页
        } else {
            String sqlTemplate = "SELECT * FROM (" +
                    "SELECT tt.*, ROWNUM AS rowno FROM (  {} ) tt WHERE ROWNUM <= {} " +
                    ") t " +
                    " WHERE t.rowno >= {} ";
            Integer page = ThreadLocal_.get(PageConstant.PARAM_OFFSET_PAGE);
            Integer size = ThreadLocal_.get(PageConstant.PARAM_OFFSET_SIZE);
            if (page == null || size == null) {
                return sql;
            }
            int start = (page - 1) * size + 1;
            int end = page * size;
            return String_.format(sqlTemplate, sql, end, start);
        }
        return sql;
    }

    public static String getCountSql(String sql) {
        String sqlTemplate = "SELECT count(*) FROM ({})";
        return String_.format(sqlTemplate, sql);
    }

    public static Boolean pageable() {
        return String_.isNotBlank(getPageType()) && Offset.getSize() > 0;
    }

    public static String getPageType() {
        Object o = ThreadLocal_.get(PageConstant.TYPE);
        if (o == null) {
            return null;
        }
        return o.toString();
    }

    public static class Count {
        public static Boolean countTotal() {
            return ThreadLocal_.get(PageConstant.TOTAL_SWITCH);
        }

        public static void setTotal(Long total) {
            ThreadLocal_.set(PageConstant.TOTAL_NUMBER, total);
        }
    }

    public static class OrderBy {
        public static String field() {
            return ThreadLocal_.get(PageConstant.PARAM_ORDERBY_FIELD);
        }

        public static Boolean asc() {
            return String_.equals(ThreadLocal_.get(PageConstant.PARAM_ORDERBY), PageConstant.OrderBy.ASC);
        }

        public static Boolean desc() {
            return !asc();
        }
    }

    public static class Offset {
        public static int getPage() {
            return ThreadLocal_.get(PageConstant.PARAM_OFFSET_PAGE);
        }

        public static int getSize() {
            return ThreadLocal_.get(PageConstant.PARAM_OFFSET_SIZE);
        }

        public static int getOffset() {
            if (getPage() < 1) {
                return 0;
            }
            return (getPage() - 1) * getSize();
        }
    }

    public static class Cursor {
        public static Long getBefore() {
            return ThreadLocal_.get(PageConstant.PARAM_CURSOR_BEFORE);
        }

        public static Long getAfter() {
            return ThreadLocal_.get(PageConstant.PARAM_CURSOR_AFTER);
        }

        public static int getLimit() {
            return ThreadLocal_.get(PageConstant.PARAM_CURSOR_LIMIT);
        }
    }
}
